import 'package:flutter/material.dart';
import 'package:jingyuan/commmon/EventBus.dart';
import 'package:jingyuan/commmon/FavoriteMgr.dart';
import 'package:jingyuan/commmon/GlobalData.dart';
import 'package:jingyuan/commmon/LocalStorage.dart';
import 'package:jingyuan/commmon/Opencc.dart';
import 'package:jingyuan/components/wdCustomTrackShape.dart';
import 'package:custom_pop_up_menu/custom_pop_up_menu.dart';
import './list.dart';
import 'package:jingyuan/PlayerManager/index.dart';
import 'package:jingyuan/commmon/Utils.dart';
import 'package:http/http.dart' as http;
import 'dart:convert' as convert;
import './PlayIconWidget.dart';
import 'package:bottom_sheet/bottom_sheet.dart';

class MainTabPage extends StatefulWidget {
  const MainTabPage({super.key});

  @override
  State<MainTabPage> createState() => _MainTabPageState();
}

class MenuItemModel {
  String id;
  String title;
  IconData icon;

  MenuItemModel(this.id, this.title, this.icon);
}

class _MainTabPageState extends State<MainTabPage> with AutomaticKeepAliveClientMixin {
  CustomPopupMenuController _moreMenuController = CustomPopupMenuController();
  MainTabListController _listController = MainTabListController();

  List<MenuItemModel> moreMenuItems = [
    // MenuItemModel("單章循環", Icons.replay),
    MenuItemModel("20", '珍藏夾', Icons.favorite_outlined),
    MenuItemModel("10", '當前位置', Icons.location_searching_rounded),
    MenuItemModel("1", '往前5秒', Icons.rotate_left),
    MenuItemModel("2", '往後5秒', Icons.rotate_right),
    MenuItemModel("3", '上一講', Icons.keyboard_arrow_left_outlined),
    MenuItemModel("4", '下一講', Icons.keyboard_arrow_right_outlined),
  ];
  PlayerManager? _playMgr;
  List<dynamic>? _tabData = null;
  var _loaded = false;
  static const _cfgKey = "jingyuan_audo_index_cfg";
  PlayIconController _playIconController = PlayIconController();
  String _searchTxt = "";
  TextEditingController _searchTextFieldController = TextEditingController();
  List<int>? _searchResult = null;

  @override
  void initState() {
    super.initState();
    _playMgr ??= PlayerManager(GlobalData.autioTabName, (v) {
      setState(() {});
    });
    setState(() {});

    FishEventBus.on<PlayCompleteEvent>().listen((event) {
      if (event.player == _playMgr) {
        _listController.playNext(1);
      }
    });
    FishEventBus.on<PlayEvent>().listen((event) {
      if (_playMgr != null && _playMgr!.isPlaying) {
        _playIconController.play();
      } else {
        _playIconController.stop();
      }
    });

    getTabCfg();
  }

  getTabCfg() async {
    _loaded = false;
    await Opencc.init();
    FavoriteMgr.getInstance().initMgr();
    var cfg = await LocalStorage.getJson(_cfgKey);
    if (cfg == null) {
      var response = await http.get(
        Uri.parse('http://www.maiyuren.com/static/more/jingyuan/index.json'),
      );
      cfg = convert.json.decode(const convert.Utf8Decoder().convert(response.bodyBytes))
          as Map<String, dynamic>;
      var items = cfg["items"] as List<dynamic>;
      for (var element in items) {
        var url = element["url"];
        element["name"] = Utils.getAudioName(url);
      }
      LocalStorage.setJson(_cfgKey, cfg);
    }

    var urlBase = cfg["urlBase"];
    GlobalData.urlBase = urlBase;
    _tabData = cfg["items"];
    if (_playMgr!.currItem == null) {
      _playMgr!.setCurrentItemWithoutPlay(_tabData![0]);
    }
    _loaded = true;
    setState(() {});
  }

  String get currPlayPos {
    if (_playMgr == null) return '00:00';
    return Utils.seconds2str(_playMgr!.playedLengthInSeconds);
  }

  String get currPlayLength {
    if (_playMgr == null) return '00:00';
    return Utils.seconds2str(_playMgr!.totalLengthInSeconds);
  }

  double get currPlayPosDouble {
    if (_playMgr == null) return 0;
    return _playMgr!.playedLengthInSeconds.toDouble();
  }

  double get currPlayLengthDouble {
    if (_playMgr == null) return 0;
    int sec = _playMgr!.totalLengthInSeconds;
    if (sec == 0) return 0.1;
    return sec.toDouble();
  }

  String get currPlayName {
    if (_playMgr == null) return '- 無 -';
    var item = _playMgr!.currItem;
    if (item == null) return '- 無 -';
    var name = item['name'];
    if (name == null) return '- 無 -';
    return name as String;
  }

  Widget _buildMoreMenu() {
    return ClipRRect(
        borderRadius: BorderRadius.circular(5),
        child: Container(
            color: const Color(0xFF4C4C4C),
            constraints: const BoxConstraints(minWidth: 120),
            child: IntrinsicWidth(
                child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: moreMenuItems
                  .map(
                    (item) => GestureDetector(
                      behavior: HitTestBehavior.translucent,
                      onTap: () {
                        // pre 5 sec
                        if (item.id == "1") {
                          var pos = currPlayPosDouble - 5;
                          if (pos < 0) pos = 0;
                          _playMgr!.setPos(pos.toInt());
                        } else if (item.id == "2") {
                          var pos = currPlayPosDouble + 5;
                          if (pos > currPlayLengthDouble) pos = currPlayLengthDouble;
                          _playMgr!.setPos(pos.toInt());
                        } else if (item.id == "3") {
                          _listController.playNext(-1);
                        } else if (item.id == "4") {
                          _listController.playNext(1);
                        } else if (item.id == '10') {
                          // 定位
                          _listController.jumpPos(-1);
                        } else if (item.id == '20') {
                          // 珍藏夾
                          showFlexibleBottomSheet(
                            minHeight: 0,
                            initHeight: 0.5,
                            maxHeight: 1,
                            context: context,
                            builder: _buildBottomSheet,
                            anchors: [0, 0.5, 1],
                            duration: const Duration(milliseconds: 400),
                            isSafeArea: true,
                          );
                        }

                        _moreMenuController.hideMenu();
                      },
                      child: Container(
                        height: 40,
                        padding: const EdgeInsets.symmetric(horizontal: 20),
                        child: Row(
                          children: <Widget>[
                            Icon(
                              item.icon,
                              size: 18,
                              color: Colors.white,
                            ),
                            Expanded(
                              child: Container(
                                margin: const EdgeInsets.only(left: 10),
                                padding: const EdgeInsets.symmetric(vertical: 10),
                                child: Text(
                                  item.title,
                                  style: const TextStyle(
                                    color: Colors.white,
                                    fontSize: 14,
                                  ),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  )
                  .toList(),
            ))));
  }

  Widget bottomPlayArea() {
    return SizedBox(
        width: MediaQuery.of(context).size.width, // 屏幕宽度
        height: 50, // 屏幕高度
        child: Container(
            decoration: const BoxDecoration(boxShadow: [BoxShadow(color: Colors.black12)]),
            child: Padding(
                padding: const EdgeInsets.all(8),
                child: Row(
                  children: [
                    PlayIconWidget(controller: _playIconController),
                    const SizedBox(width: 8),
                    Expanded(
                        flex: 1,
                        child: Padding(
                          padding: const EdgeInsets.only(left: 8, right: 8),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Row(
                                children: [
                                  SizedBox(
                                    child: Text(
                                      currPlayPos,
                                      style: const TextStyle(fontSize: 9),
                                    ),
                                  ),
                                  Expanded(
                                      flex: 1,
                                      child: Text(
                                        currPlayName,
                                        softWrap: false,
                                        textAlign: TextAlign.center,
                                        style: const TextStyle(
                                            fontSize: 9, overflow: TextOverflow.ellipsis),
                                      )),
                                  SizedBox(
                                    child: Text(
                                      currPlayLength,
                                      style: const TextStyle(fontSize: 9),
                                    ),
                                  ),
                                ],
                              ),
                              SliderTheme(
                                data: SliderThemeData(
                                  trackHeight: 1,
                                  inactiveTrackColor: Colors.black12,
                                  activeTrackColor: Colors.blue,
                                  disabledActiveTrackColor: Colors.blue,
                                  disabledInactiveTrackColor: Colors.blue,
                                  thumbColor: Colors.white,
                                  overlayShape: const RoundSliderOverlayShape(overlayRadius: 0),
                                  trackShape: WDCustomTrackShape(addHeight: 0),
                                ),
                                child: Slider(
                                  value: currPlayPosDouble,
                                  max: currPlayLengthDouble,
                                  onChanged: (value) {
                                    if (value.compareTo(currPlayPosDouble) != 0) {
                                      _playMgr?.setPos(value.toInt());
                                    }
                                  },
                                ),
                              ),
                            ],
                          ),
                        )),
                    IconButton(
                        padding: EdgeInsets.zero,
                        onPressed: () {
                          if (_playMgr!.isPlaying) {
                            _playMgr!.pause();
                          } else {
                            _playMgr!.resume();
                          }
                        },
                        icon: Icon(_playMgr!.isPlaying ? Icons.pause_outlined : Icons.play_arrow)),
                    CustomPopupMenu(
                      menuBuilder: _buildMoreMenu,
                      barrierColor: Colors.transparent,
                      pressType: PressType.singleClick,
                      controller: _moreMenuController,
                      child: const Icon(Icons.more_vert_outlined),
                    ),
                  ],
                ))));
  }

  Widget _buildBottomSheet(
    BuildContext context,
    ScrollController scrollController,
    double bottomSheetOffset,
  ) {
    return Material(
      child: Container(
        padding: const EdgeInsets.only(top: 8, bottom: 8, left: 16, right: 16),
        child: ListView(
          controller: scrollController,
          children: List.generate(FavoriteMgr.getInstance().size(), (i) {
            int pos = FavoriteMgr.getInstance().getItemByIndex(i);
            var item = _tabData![pos];
            return GestureDetector(
                onTap: () {
                  _listController.jumpPos(pos);
                  Navigator.pop(context);
                },
                child: SizedBox(
                    height: 40,
                    child: Row(children: [
                      const Icon(Icons.favorite_outline),
                      const SizedBox(
                        width: 8,
                      ),
                      Expanded(
                          child: Text(
                        '${pos + 1}. ${item["name"]}',
                        overflow: TextOverflow.ellipsis,
                      ))
                    ])));
          }),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: !_loaded
            ? const Text("加載中...")
            : Column(children: [
                Container(
                    padding: const EdgeInsets.only(left: 8, right: 8),
                    decoration: const BoxDecoration(color: Colors.white, boxShadow: [
                      BoxShadow(
                          color: Color(0xFFe8E8E8),
                          offset: Offset(0, 0.5),
                          blurRadius: 0.5,
                          spreadRadius: 0.5)
                    ]),
                    child: Row(children: [
                      Expanded(
                          child: TextField(
                        controller: _searchTextFieldController,
                        scrollPadding: EdgeInsets.zero,
                        decoration: const InputDecoration(
                            hintText: '輸入數字/漢字搜尋',
                            border: InputBorder.none,
                            prefixIcon: Icon(Icons.search)),
                        onChanged: (value) {
                          var coreV = value.trim();
                          _listController.search(coreV);
                          _searchTxt = coreV;
                          setState(() {});
                        },
                      )),
                      _searchTxt.isNotEmpty
                          ? IconButton(
                              padding: EdgeInsets.zero,
                              onPressed: () {
                                _searchTextFieldController.clear();
                                _searchTxt = "";
                                _listController.search(_searchTxt);
                                setState(() {});
                              },
                              icon: const Icon(Icons.close))
                          : const SizedBox(width: 0),
                      _searchResult != null && _searchResult!.isNotEmpty
                          ? IconButton(
                              padding: EdgeInsets.zero,
                              onPressed: () {
                                _listController.goNextSearchResult(-1);
                              },
                              icon: const Icon(Icons.arrow_upward))
                          : const SizedBox(width: 0),
                      _searchResult != null && _searchResult!.isNotEmpty
                          ? IconButton(
                              padding: EdgeInsets.zero,
                              onPressed: () {
                                _listController.goNextSearchResult(1);
                              },
                              icon: const Icon(Icons.arrow_downward))
                          : const SizedBox(width: 0),
                    ])),
                Expanded(
                    child: Padding(
                        padding: const EdgeInsets.only(top: 2),
                        child: MainTabList(
                          datas: _tabData!,
                          cb: (item) {
                            if (_playMgr != null) {
                              var name = item["name"];
                              if (name == currPlayName) {
                                if (_playMgr!.isPlaying) {
                                  _playMgr?.pause();
                                } else {
                                  _playMgr!.resume();
                                }
                              } else {
                                _playMgr!.play(item);
                              }
                            }
                          },
                          searchCb: (data) {
                            _searchResult = data;
                            setState(() {});
                          },
                          controller: _listController,
                          playerManager: _playMgr!,
                        ))),
                bottomPlayArea(),
              ]));
  }

  @override
  bool get wantKeepAlive => true;
}
